Store.addConnection   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
import Database from "./Database";
2
import Table from "./Table";
3
import Connection from "./Connection";
4
import Index from "./Table/Index";
5
import {ConnectionInterface, DatabaseInterface, StoreInterface} from "../JeloquentInterfaces";
6
7
/**
8
 *
9
 */
10
class Store implements StoreInterface {
11
12
    classInstances: object;
13
14
    numberOfModelCreated: number;
15
16
    private connections: Map<string, ConnectionInterface>;
17
18
    private databases: Map<string, DatabaseInterface>;
19
20
    private useConnectionName: string;
21
22
    private useDatabase: string;
23
24
    constructor() {
25
        this.classInstances = {};
26
        this.databases = new Map();
27
        this.connections = new Map();
28
        this.numberOfModelCreated = 0;
29
        this.useDatabase = 'default';
30
        this.useConnectionName = 'default';
31
        globalThis.Store = this;
32
    }
33
34
    add(database: DatabaseInterface): void {
35
        this.databases.set(database.name, database);
36
    }
37
38
    addConnection(connection: ConnectionInterface, name = 'default'): void {
39
        this.connections.set(name, connection);
40
    }
41
42
    connection(): ConnectionInterface|null {
43
        return this.connections.get(this.useConnectionName) ?? null;
44
    }
45
46
    database(): DatabaseInterface|null {
47
        if (!this.databases.has(this.useDatabase)) {
48
            return null;
49
        }
50
        return new Proxy(this.databases.get(this.useDatabase), {
51
            construct(target, argArray, newTarget): object {
52
                return Reflect.construct(target, argArray, newTarget);
53
            },
54
55
            get(target: Database, p): unknown {
56
                if (!target[p]) {
57
                    return (...args) => {
58
                        const arrayArgs = [...args];
59
                        const tableName = arrayArgs.shift();
60
                        return target.table(tableName)[p](...arrayArgs);
61
                    }
62
                }
63
                return Reflect.get(target, p);
64
            }
65
        }) as DatabaseInterface;
66
    }
67
68
    use(storeName = 'default'): void {
69
        this.useDatabase = storeName;
70
        this.databases.get(this.useDatabase)?.setIndexes();
71
    }
72
73
    useConnection(name = 'default'): void {
74
        this.useConnectionName = name;
75
    }
76
77
    /**
78
     * @deprecated
79
     */
80
    useConnections(name:string): void {
81
        this.useConnection(name);
82
    }
83
}
84
85
86
export {
87
    Store,
88
    Database,
89
    Table,
90
    Connection,
91
    Index,
92
};